CREATE OR REPLACE FUNCTION %TRIGGER_NAME%_func()
RETURNS trigger AS
$BODY$
DECLARE
    xmldoc  text;
    new_val xml;
    old_val xml;
    op      char(1);
BEGIN
    IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
        xmldoc := '<row tableName="%TABLE_NAME%" xmlns="http://www.matasek.net/DatabaseLogger" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        
        %LOGGING_TRIGGER_LOOP_NEW%  
        
        xmldoc := xmldoc || '</row>';
        
        new_val := xmldoc::xml;
    ELSE
        new_val := NULL;
    END IF;


    IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
        xmldoc := '<row tableName="%TABLE_NAME%" xmlns="http://www.matasek.net/DatabaseLogger" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
        
        %LOGGING_TRIGGER_LOOP_OLD%  
        
        xmldoc := xmldoc || '</row>';
        
        old_val := xmldoc::xml;
    ELSE
        old_val := NULL;
    END IF;


    IF TG_OP = 'INSERT' THEN
        op  := 'I';
    ELSIF TG_OP = 'UPDATE' THEN
        op := 'U';     
    ELSIF TG_OP = 'DELETE' THEN
        op := 'D';     
    END IF;

    
    INSERT INTO
        %LOGGING_TABLE_NAME% (table_name, operation, old_values, new_values)
    VALUES
        ('%TABLE_NAME%', op, old_val, new_val);

    RETURN new;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;


CREATE TRIGGER %TRIGGER_NAME%
  AFTER %TRIGGER_EVENTS% 
  ON %TABLE_NAME%
  FOR EACH ROW
  EXECUTE PROCEDURE %TRIGGER_NAME%_func();
